﻿using System;
using System.Linq.Expressions;
using Fuse8.DomainFramework.BusinessService;

using Fuse8.ContentManagementFramework.Domain;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.ContentManagementFramework.BizFacade.Services
{
    public abstract class CmsSiteBusinessService<T> : CmsBusinessService<T> where T : CmsSiteEntityObject, new()
    {
        private Expression<Func<T, bool>> slicer;

        protected Expression<Func<T, bool>> Slicer
        {
            get
            {
                if (slicer == null)
                {
                    var contextSite = DependencyServiceLocator.Current.GetInstance<ICmsContext>().ContextSite;
                    slicer =
                        p =>
                        (p.SiteGroupId == null && p.SiteId == null) ||
                        (p.SiteGroupId == contextSite.SiteGroupId && p.SiteId == null) ||
                        (p.SiteGroupId == contextSite.SiteGroupId && p.SiteId == contextSite.Id);
                }
                return slicer;
            }
        }

        protected override void OnCreating(EntityPreEventArgs<T, int> e)
        {
            base.OnCreating(e);

            SiteAwareEntityObjectMediator.SetSiteEntityByCategory(e.Entity, e.Entity.SiteCategory);
        }

        protected override void OnUpdating(EntityPreEventArgs<T, int> e)
        {
            base.OnUpdating(e);

            SiteAwareEntityObjectMediator.SetSiteEntityByCategory(e.Entity, e.Entity.SiteCategory);
        }
    }
}
